import 'dart:io';

import 'package:dio_cache_interceptor_hive_store/dio_cache_interceptor_hive_store.dart';
import 'package:enterprise_v6_app/app/core/constans/storage.dart';
import 'package:enterprise_v6_app/app/core/utils/hover_button_util.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/location_util.dart';
import 'package:enterprise_v6_app/app/core/utils/log_util.dart';
import 'package:enterprise_v6_app/app/core/utils/storage_util.dart';
import 'package:enterprise_v6_app/app/data/entities/auth/login_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/auth/user_login_entity.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';
import 'package:get/get.dart';

abstract class UserManager {
  static void init() {
    _isLoggedIn = getToken() != null && getUser() != null;
    // _isLoggedIn =  getUser() != null;
  }

  /// 用户信息, 可利用 ObxValue 监听数据变化
  static final _userEntity = Rxn<LoginEntity>();

  static String? _token;

  static late bool _isLoggedIn;

  static Rxn<LoginEntity> get rxUserEntity => _userEntity;

  /// 是否登录了
  static bool get isLoggedIn => _isLoggedIn;

  /// 退出登录，清空缓存数据
  static void logout() async {
    await clearDioCache();
    AppLogger.log('[UserManager.logout()] 退出登录，清除用户信息');
    removeUserInfo();
  }

  /// 清除和重置相关用户数据
  static void removeUserInfo() {
    _isLoggedIn = false;
    _token = null;
    _userEntity.value = null;
    HoverButtonUtil.closeHover();
    Interface.tilesetUrl = '';
    Interface.terrainUrl = '';
    StorageUtil.removeAll([StorageConstants.userInfo, StorageConstants.authenticationToken]);
    Get.offAllNamed(AppRoutes.authLogin);
  }

  /// 清除token
  static void removeToken() {
    StorageUtil.removeAll([StorageConstants.authenticationToken]);
  }

  /// 清除dio缓存
  static Future<void> clearDioCache() async {
    // await MemCacheStore().clean();
    // 清理磁盘缓存
    await HiveCacheStore(Directory.systemTemp.path).clean();
  }

  /// 进行登录
  static void login(LoginEntity userEntity) {
    _isLoggedIn = true;
    _userEntity.trigger(userEntity);
    // saveUser(userEntity).whenComplete(() {
    // ... 继续其他设置, 例如埋点
    // });
  }

  /// 保存用户信息
  static Future<void> saveUser(LoginEntity userEntity) async {
    _isLoggedIn = true;
    _userEntity.trigger(userEntity);
    await StorageUtil.setJSON(StorageConstants.userInfo, userEntity.toJson());
  }

  static LoginEntity? getUser() {
    _userEntity.value ??= StorageUtil.getEntity<LoginEntity>(StorageConstants.userInfo);
    return _userEntity.value;
  }

  static Future<void> saveToken(String? token) async {
    if (token != null) {
      _token = token;
      await StorageUtil.setString(StorageConstants.authenticationToken, token);
    }
  }

  static String? getToken() {
    _token ??= StorageUtil.getString(StorageConstants.authenticationToken);
    return _token;
  }

  /// 调用网络接口请求用户信息
  static Future<bool> requestUserInfo() async {
    // 请求接口
    // 保存用户信息
    return true;
  }

  static String? getUserId() {
    return _userEntity.value?.systemUser?.id;
  }

  static bool isCurrentUser(String? userId) => getUserId() == userId;

  /// 保存登录账户密码
  static void saveLoginCredential(String usr, String pwd) {
    // 获取已保存的账户密码列表数据
    final loginList = getLoginCredentialList();
    // 判断列表中是否存在相同名称账号,存在则先移除
    loginList.removeWhere((element) => element.userName == usr);
    final userLoginEntity = UserLoginEntity();
    userLoginEntity.userName = usr;
    userLoginEntity.passWord = pwd;
    // 添加到第一位
    loginList.insert(0, userLoginEntity);
    StorageUtil.setJSON(StorageConstants.loginCredentialList, loginList);
  }

  /// 移除历史账号
  static void removeLoginCredential(String usr) {
    // 获取已保存的账户密码列表数据
    final loginList = getLoginCredentialList();
    loginList.removeWhere((element) => element.userName == usr);
    StorageUtil.setJSON(StorageConstants.loginCredentialList, loginList);
  }

  /// 获取登录账户密码
  static List<UserLoginEntity> getLoginCredentialList() {
    return StorageUtil.getEntity<List<UserLoginEntity>>(StorageConstants.loginCredentialList) ?? [];
  }
}
